﻿using CommonHttpServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using flyticketBase;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace flypeachTicketServer
{
    public class flypeachTicketQuery : IQueryTicket
    {
        public flypeachTicketQuery(CookieContainer coo) : base(coo)
        {
            this._LoginServer.Cookies = coo;
            this._LoginServer.Host = "booking.flypeach.com";
        }
        public flypeachTicketQuery()
        {
            this._LoginServer.Host = "booking.flypeach.com";
        }
        public override void Init()
        {
            this._LoginServer.Url = "https://booking.flypeach.com/cn";
            this._LoginServer.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
            this._LoginServer.AcceptEncoding = "gzip, deflate, br";
            this._LoginServer.AcceptLanguage = "zh-CN,zh;q=0.9";
            this._LoginServer.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36";
            //"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0" 
            this._LoginServer.HeaderCollection.Add("Upgrade-Insecure-Requests", "1");
            base.Init();
            this._Result = this._LoginServer.GetHttpResult();
        }

        public override string QueryTicket(string[] go, bool is_return, DateTime date1, DateTime? date2)
        {
            throw new NotImplementedException();
        }

        public override string QueryTicket(string go, string at, bool is_return, DateTime date1, DateTime? date2)
        {
            this._LoginServer.AcceptEncoding = "gzip, deflate, br";
            this._LoginServer.AcceptLanguage = "zh-CN,zh;q=0.9";
            this._LoginServer.Allowautoredirect = true;
            this._LoginServer.HeaderCollection.Add("Cache-Control", "max-age=0");
            this._LoginServer.Expect100Continue = false;
            this._LoginServer.Url = "https://booking.flypeach.com/cn/search";
            this._LoginServer.PostData = "flight_search_parameter%5B0%5D%5B"
                + "departure_date%5D=" + date1.ToString("yyyy/MM/DD").Replace("/", "%2F")//2018%2F07%2F27
                + "&flight_search_parameter%5B0%5D%5B"
                + "departure_airport_code%5D=" + go.ToUpper()
                + "&flight_search_parameter%5B0%5D%5B"
                + "arrival_airport_code%5D=" + at.ToUpper()
                + "&flight_search_parameter%5B0%5D%5B"
                + "is_return%5D=" + is_return
                + "&flight_search_parameter%5B0%5D%5B"
                + "return_date%5D=" + date2?.ToString("yyyy/MM/DD").Replace("/", "%2F")
                + "&adult_count=1"
                + "&child_count=0&infant_count=0";
            this._LoginServer.Method = "post";
            //this._LoginServer.HeaderCollection.Remove("Upgrade-Insecure-Requests");
            this._LoginServer.Origin = "https://booking.flypeach.com";
            this._LoginServer.Referer = "https://booking.flypeach.com/cn";
            this._Result = this._LoginServer.PostHttpResult();
            this._LoginServer.Origin = "";
            this._LoginServer.Url = " https://booking.flypeach.com/cn/flight_search";
            this._Result = this._LoginServer.GetHttpResult();
            return _Result.Html;
        }

        public override List<TicketDetail> AnalyseHtml(string html, out ResponseTag info)
        {
            info = new ResponseTag();
            List<TicketDetail> list = new List<TicketDetail>();
            string flyways = null;
            try
            {
                var match = Regex.Match(html, @"var flightResults = \[(?<fly>.*\])\]");
                flyways = match.Groups["fly"].Value;
                if (string.IsNullOrEmpty(flyways))
                {
                    info.errcode = ErrCode.Fatal;
                    info.Msg = html;
                }
                List<flypeachflightResults> l = JsonConvert.DeserializeObject<List<flypeachflightResults>>(flyways);
                if (l != null)
                    foreach (var item in l)
                    {
                        list.Add(new TicketDetail() { PlatEx = item });
                    }

            }
            catch (Exception ex)
            {
                info.Msg = ex.Message;
            }
            finally
            {
                if (string.IsNullOrEmpty(html) || html.Contains("booking.flypeach.com - Browser error"))
                {
                    info.errcode = ErrCode.Fatal;
                    info.Msg = html;
                }
            }

            return list;
        }
    }
}
